'''
2018/2/23 修改原来无法读取有换行符的txt文件 主要涉及txt文件读取，str转list，np中字符串转16进制字节串,字节串转浮点数。
TODO：余总写了一个C#的界面可以实时分析，只有也用TK做一个实时分析界面，
点击绘制图形的一个工能就很完善了，多线程使画图不阻塞
然后可以把程序重构一下，用子函数和类
疑问？：只有np才能实现字符串转16进制字节串,字节串转浮点数吗？
'''
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# import string
# from ctypes import *
# import struct
# import inspect
# import re
# def convert(s):
#     i = int(s, 16)                   # convert from hex to a Python int
#     cp = pointer(c_int(i))           # make this into a c integer
#     fp = cast(cp, POINTER(c_float))  # cast the int pointer to a float pointer
#     return fp.contents.value         # dereference the pointer, get the float

filename="E:\\OneDrive\\learn\\DataProcess\\monidata.txt"
'''方法1 读取文件 读取后格式为一整个str，对文件宽容度较高 推荐使用'''
with open(filename, "r") as f:
    text = f.read()
a=text
a=a.replace("\n"," ")#替换掉换行符 改成空格，只运行a.replace() a是不会变的 必须要a=a.replace()
a=a.split(" ")#str转换成list 以空格划分
'''删除多余的空元素'''
while '' in a:
    a.remove('')
print(type(a),a)
'''方法2 numpy读取文件  读取后格式为list（按空格划分）,但是文本文件中的每一行必须含有相同的数据限制很高'''
##a = np.loadtxt(filename,dtype=np.int16)#不行 16进制不能直接转换
# a = np.loadtxt(filename,dtype=str) #字符格式 文本文件中的每一行必须含有相同的数据
# print(type(a),a)
# # a = np.loadtxt(filename,dtype=bytes)#j字节流
# # print(a,a[1],a.shape)
# # b=[]
# # for i in a:
# #     # print(type(int(i, 16)))
# #     b.append(int(i, 16))
# # b=np.array(b)
# # print(a.shape)
'''!!!np的方法可用直接操作list格式的数据'''
'''自动以AA为头划分数据'''
bb=np.where(a=="AA")
cc=np.split(a,bb[0][1:])
#dd=np.array([])#创建一个空数组 
dd=[]
#TODO:可不可以不用for 有没有更好的方法
for i in range(len(cc)):
    #print(i)
    if(len(cc[i])==138):
        #print(cc[i])
        #dd=np.append(dd,cc[i])#不断往里加，相当与拼接一个一维数组 ！！！拼接非常慢最好不要用
        dd.append(cc[i])#numpy的append不能实现添加 而是拼接 先用list 然后转换 TODO:可不可以只用numpy?
dd=np.array(dd)  
b=dd
#b=a.reshape((-1,138)) #用形状重排
RTK_data=[]
'''按组把数据处理好后进行解析数据'''
for i in range(len(b)):
    # print(i)
    Version=''.join(b[i][2:4])#连接字符
    Length=''.join(b[i][4:6])
    Freq=''.join(b[i][6:8])
    Time_utc=''.join(b[i][8:12])
    Year_utc=''.join(b[i][12:14])
    Month_utc=''.join(b[i][14:16])
    Day_utc=''.join(b[i][16:18])
    Hour_utc=''.join(b[i][18:20])
    Min_utc=''.join(b[i][20:22])
    Sec_utc=''.join(b[i][22:24])
    Lat=''.join(b[i][24:32])
    Lon=''.join(b[i][32:40])
    Alt=''.join(b[i][40:48])
    Eph=''.join(b[i][48:52])
    Epv=''.join(b[i][52:56])
    Vel_earth=''.join(b[i][56:60])
    Angle_TrackTrue=''.join(b[i][60:64])
    Angle_Heading=''.join(b[i][64:68])
    Angle_Pitch=''.join(b[i][68:72])
    Vel_n=''.join(b[i][72:80])
    Vel_e=''.join(b[i][80:88])
    Vel_u=''.join(b[i][88:96])
    Satellites_used=''.join(b[i][96:98])
    Satellites_track=''.join(b[i][98:100])
    Vel_ned_valid=''.join(b[i][100:104])
    Fix_type=''.join(b[i][104:106])
    Head_state=''.join(b[i][106:110])
    Head_deviation=''.join(b[i][110:114])
    INS_state=''.join(b[i][114:116])
    Checksum=''.join(b[i][136:138])
    list=[Version,Length,Freq,Time_utc,Year_utc,Month_utc,Day_utc,Hour_utc,Min_utc,Sec_utc,Lat,Lon,Alt,Eph,Epv,Vel_earth,Angle_TrackTrue,Angle_Heading,Angle_Pitch,Vel_n,Vel_e,Vel_u,Satellites_used,Satellites_track,Vel_ned_valid,Fix_type,Head_state,Head_deviation,INS_state,Checksum]
    list1=['Version', 'Length', 'Freq', 'Time_utc', 'Year_utc', 'Month_utc', 'Day_utc', 'Hour_utc', 'Min_utc', 'Sec_utc', 'Lat', 'Lon', 'Alt', 'Eph', 'Epv', 'Vel_earth', 'Angle_TrackTrue', 'Angle_Heading', 'Angle_Pitch', 'Vel_n', 'Vel_e', 'Vel_u', 'Satellites_used', 'Satellites_track', 'Vel_ned_valid', 'Fix_type', 'Head_state', 'Head_deviation', 'INS_state', 'Checksum']
    print(list1.index('Vel_n'))
    '''字符串转16进制字节串'''
    #bytes().fromhex(Time_utc)#字符串转16进制字节串
    '''字节串转浮点数'''
    #np.frombuffer( b'\x01\x02\x31\x32' , np.float32) 字节串转浮点数
    RTK_list=[] 
    for j,i in zip(list1,list):
        if len(i)==4:
            # print(j,"=",np.frombuffer( bytes().fromhex(i) , np.int16) )
            RTK_list.append( np.frombuffer( bytes().fromhex(i) , np.int16))
        elif len(i)==8:
            # print(j,"=",np.frombuffer( bytes().fromhex(i) , np.float32) )
            RTK_list.append( np.frombuffer( bytes().fromhex(i) , np.float32) )
        elif len(i)==16:
            # print(j,"=",np.frombuffer( bytes().fromhex(i) , np.float64) )
            RTK_list.append( np.frombuffer( bytes().fromhex(i) , np.float64) )
    RTK_data.append(RTK_list) 
c=np.array(RTK_data)
c=c.reshape(-1,30)
'''清除数据为0的行'''
# print(c.shape)
d=np.where(c[:,3]==0)
e=np.delete(c, d, axis=0)
print(len(e))

'''取矩阵的某一列'''
x=e[:,10]
y=e[:,11]
z=e[:,12]
vn=e[:,19]
ve=e[:,20]
vu=e[:,21]
zing_time=e[:,3]
print(x)
print(y)
print(z)
print(vn)
print(ve)
print(vu)

'''画图'''
plt.style.use("ggplot")
# fig = plt.figure()
# ax = Axes3D(fig)
# ax.scatter(x,y,z,c='r')
# ax.view_init(elev=10., azim=11)#3D图的初始视角，视角可以用鼠标拖动
plt.plot(zing_time,e[:,17])
plt.show()
print("end")




#print(np.frombuffer( b'\xc7\x4d\x3b\x23\x83\x08\x5e\x40', np.float64) )
# print("Version=",np.frombuffer( bytes().fromhex(Version) , np.int16) )#2位
# print("Length=",np.frombuffer( bytes().fromhex(Length) , np.int16) )
# print("Freq=",np.frombuffer( bytes().fromhex(Freq) , np.int16) )
# print("Time_utc=",np.frombuffer( bytes().fromhex(Time_utc) , np.int32))
# print("Year_utc=",np.frombuffer( bytes().fromhex(Year_utc) , np.int16))
# print("Month_utc=",np.frombuffer( bytes().fromhex(Month_utc) , np.int16))
# print("Lat=",np.frombuffer( bytes().fromhex(Lat) , np.float64) )
# print("Lon=",np.frombuffer( bytes().fromhex(Lon) , np.float64) )
# print("Alt=",np.frombuffer( bytes().fromhex(Alt) , np.float64) )

# reg=re.compile(r"b\'(.*?)\'",re.S)
# for i in b:
#     for ii in re.findall(reg,str(i)):
#         print (str(binascii.a2b_hex(str(ii))))


